package com.yj.netty.chapter04;

import com.yj.netty.chapter02.User;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.List;

public class CustomDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        // 标识符
        int flag = in.readInt();
        // 指令
        byte cmd  = in.readByte();
        // 数据长度
        int length = in.readInt();
        // 数据
        byte[] data = new byte[length];
        in.readBytes(data);


        ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(data));
        User user = (User) objectInputStream.readObject();


        System.out.println("receive user: " + user);
        objectInputStream.close();

        out.add(user);
    }
}
